package com.iheima.reggie_take.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iheima.reggie_take.common.R;
import com.iheima.reggie_take.entity.Category;
import com.iheima.reggie_take.entity.Employee;
import com.iheima.reggie_take.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * ClassName: GategoryController
 * Package: com.iheima.reggie_take.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-01-17
 * Time: 14:51
 */

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //新增菜品 Post localhost:8080/category  已经写好了type=1
    //新增套餐分类 Post location:8080/category type=2  请求路径是一样的 关键就是type
    @PostMapping
    public R<String> save(@RequestBody Category category){
        //这些返回结果 都是前端接收怎么样的数据 后端就怎么返回
        categoryService.save(category);
        return R.success("新增分类成功");
    }


    //分页查询
    //GET /category/page?page=1&pageSize=10
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //条件构造器 排序条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.orderByAsc(Category::getSort);
        //进行分页查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    //删除分类 前提是当前分类是否关联了菜品或者套餐
    //category?ids=1413341197421846529
    @DeleteMapping
    public R<String> delete(Long ids){
        System.out.println(ids);
        //categoryService.removeById(ids);
        categoryService.remove(ids);
        return R.success("分类信息删除成功！");
    }

    //根据id进行修改
    // 方法是Put localhost:8080/category
    @PutMapping
    public R<String> update(@RequestBody Category category){
        //前端传来的JSON数据
        categoryService.updateById(category);

        return R.success("修改分类信息成功");
    }


    /**
     * 根据条件查询菜品分类数据
     * category/list
     * 点击新建菜品就会发出请求
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> listR(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        //添加排序条件 前面的优先排序  相等之后 后面才排序
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);

        return R.success(list);
    }


}
